#include <stdio.h>
#include <pthread.h>
#include "queue.h"
#include <semaphore.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
QUEUE *queue;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
sem_t sem;

void add_sql_to_queue(char *sql)
{
	pthread_mutex_lock(&mutex);
	queue_add(queue,sql);
	pthread_mutex_unlock(&mutex);
	sem_post(&sem);
}

void* add_sql(void* arg)
{
	printf("add_sql!\n");
	for(int i=0;i<100;i++)
	{
		char cmd[100]={0};
		snprintf(cmd,sizeof(cmd)-1,"sql%d",i);
		add_sql_to_queue(cmd);
	}
}

void* print_sql(void* arg)
{
	while(1)
	{
		if (sem_wait(&sem))
		{
			if(errno==EINTR)
				continue;
			printf("error occer\n");
		}
		else
		{
			pthread_mutex_lock(&mutex);
			char* data = queue_out(queue);
			pthread_mutex_unlock(&mutex);
			if(data != NULL)
			{
				printf("%s\n",data);
				free(data);
			}
			else
			{
				printf("data = NULL");
			}
		}
	}
}


int main(void)
{
	pthread_t thread;
	queue = queue_new();
	sem_init(&sem,0,0);
	pthread_create(&thread,NULL,print_sql,NULL);
	sleep(1);
	pthread_create(&thread,NULL,add_sql,NULL);
	pthread_create(&thread,NULL,add_sql,NULL);
	sleep(1);
	pthread_create(&thread,NULL,add_sql,NULL);
	sleep(10);
}
